import React, {  
	Component
} from 'react';
import echarts from 'echarts';

import  './style/portrait.less';
import {fetchRequest} from '../common'
 
/* 以类的方式创建一个组件 */
class Portrait extends Component {
	constructor(props) {
		super(props);
		this.state = {
			realTimeUserMan: 0,
			totalUserMan: '',
			realTimeUserWoman: 0,
			totalUserWoman: '',
            professionArr:[],
            professionNumber:[],
            educationArr:[],
            educationNumber:[],

		};
	}
	/**
	 * 在初始化渲染执行之后立刻调用一次，仅客户端有效（服务器端不会调用）。
	 * 在生命周期中的这个时间点，组件拥有一个 DOM 展现，
	 * 你可以通过 this.getDOMNode() 来获取相应 DOM 节点。
	 */

	componentDidMount() {
		this.loadChart();
        let $that=this;
        var FetchData=fetchRequest('/login','POST',{'mobile':'13612345678','password':'admin'});
          FetchData.then(function(re){
           let token=re.token;
           $that.setState({
             token:token
            });
          
            
       },function(er){
         	console.log(er);
       });
   $that.loadNumberGender();
	}
    componentWillUpdate() {
      
        
    }
		
	//性别比例
    loadNumberGender() {
     let $that = this;
     let FetchData_gender = fetchRequest('/group', 'POST', { 'gender': 1 }, { 'token': this.state.token });
     let FetchData_profession = fetchRequest('/group', 'POST', { 'profession': 1 }, { 'token': this.state.token });
     let FetchData_education = fetchRequest('/group', 'POST', { 'education': 1 }, { 'token': this.state.token });
     //性别比例
     FetchData_gender.then(function(re) {
     	console.log(re)
         if (re.code==0) {
             let ele="人数";
             $that.setState({
                 totalUserMan: re.list[0][ele],
                 totalUserWoman: re.list[1][ele]
             });
         } else {
            console.log(re.msg)
         }

     }, function(er) {
         console.log(er);
     });
     //行业比例
     FetchData_profession.then(function(re) {
         console.log(re);
         if (re.code == 0) {
             let field_1 = "行业";
             let field_2 = "人数";
             let arr = re.list;
             let arr_new = new Array();
             let number_new = new Array();
             arr.forEach((item, index) => {
                 arr_new.push(item[field_1]);
                 number_new.push(item[field_2]);
             })
             $that.loadChartProfession(arr_new,number_new);//身份
             $that.setState({
                 professionArr: arr_new,
                 professionNumber: number_new
             });


             console.log($that.state);
         } else {
             alert(re.msg)
         }
     }, function(er) {
         console.log(er);
     });
     //教育程度比例
     FetchData_education.then(function(re) {
        console.log(re)
         if (re.code == 0) {
             let field_1 = "学历";
             let field_2 = "人数";
             $that.setState({
                
             });
         } else {
             alert(re.msg);
         }
     }, function(er) {
         console.log(er);
     });
 }
 /*
*表格
*/
	loadChart(e) {
        
     
		this.loadChartAge();
		//this.loadChartProfession(); //身份
		//this.loadChartsEducation(x,y);
		this.loadChartsStage();
        this.loadChartsSalary();
        
	}

	loadChartAge() {
		let myChart = echarts.init(document.getElementById('chart-age'));
		let option = {
			title: {
				text: ''//基础雷达图
			},
			tooltip: {},
			legend: {
				data: []//'预算分配（Allocated Budget）', '实际开销（Actual Spending）'
			},
			radar: {
				// shape: 'circle',
				name: {
					textStyle: {
						color: '#fff',
						backgroundColor: '#999',
						borderRadius: 3,
						padding:[3, 2]
					}
				},
				indicator: [{
					name: '14-19岁'
				}, {
					name: '20-24岁'
				}, {
					name: '25-29岁'
				}, {
					name: '30-34岁'
				}, {
					name: '35-39岁'
				}, {
					name: '40-44岁'
				}, {
					name: '45-49岁'
				}, {
					name: '其他年龄'
				}],
				splitNumber: 4,
				splitArea: {
					areaStyle: {
						color: ['rgba(127, 153, 255, 0.2)', 'rgba(0, 0, 0, 0)']
					}
				}
			},
			series: [{
				name: '预算 vs 开销（Budget vs spending）',
				type: 'radar',
				// areaStyle: {normal: {}},
				data: [{
					value: [200, 100, 100, 100, 200, 100, 200, 50000],
					name: '预算分配（Allocated Budget）'
				}],
				areaStyle: {
					color: '#9AFFF9',
					opacity: 0.2
				},
				lineStyle: {
					color: '#73BFDF'
				}
			}]
		};
		myChart.setOption(option);

		window.addEventListener('resize', e => {
			myChart.resize();
		});
	}
    //身份职业
    loadChartProfession(){
     let myChart = echarts.init(document.getElementById('chart-profession'));
     let option = {
         color: 'rgba(39,108,117,0.8)',
         textStyle: {
             normal: {
                 color: '#fff'
             }
         },
         title: {
             text: '', //标题1
             subtext: '' //标题2
         },
         tooltip: {
             trigger: 'axis'
         },
         legend: {
             data: ['人数']
         },
         calculable: true,
         xAxis: [{
             type: 'category',
             data:[1,2],
             // x轴的字体样式
             axisLabel: {
                 show: true,
                 textStyle: {
                     color: '#E9F1FB',

                 }
             },
             // 控制网格线是否显示
             splitLine: {
                 show: false,
                 //  改变轴线颜色
                 lineStyle: {
                     // 使用深浅的间隔色
                     color: ['red']
                 }
             },
             // x轴的颜色和宽度
             axisLine: {
                 lineStyle: {
                     color: '#E9F1FB',

                 }
             }
         }],
         yAxis: [{
             type: 'value',
             // x轴的字体样式
             axisLabel: {
                 show: true,
                 textStyle: {
                     color: '#E9F1FB',

                 }
             },
             // x轴的颜色和宽度
             axisLine: {
                 lineStyle: {
                     color: '#fff',

                 }
             }
         }],
         series: [{
             name:'收入',
             type:'bar',
             data:[3,4],
             barWidth: 26,
             // markPoint: {
             //     data: [
             //         { name: '最高', value: 480, xAxis: 8, yAxis: 500, symbolSize: 18 },
             //         { name: '最低', value: 22, xAxis: 11, yAxis: 300 }
             //     ]
             // },
             // markLine: {
             //     data: [
             //         { type: 'average', name: '平均值' }
             //     ]
             // },
         }]
     };
   
     myChart.setOption(option);
     window.addEventListener('resize', e => {
         myChart.resize();
     });
    }
	//收入水平分布
	loadChartsSalary(x,y){
		 let myChart = echarts.init(document.getElementById('chart-salary'));
         let option = {
             textStyle: {
                 normal: {
                     color: '#fff'
                 }
             },
             tooltip: {

                 trigger:'axis',
                 axisPointer: { // 坐标轴指示器，坐标轴触发有效
                     type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                 }
             },
             
             toolbox: {
                 show:false,
                 feature: {
                     mark: { show: true },
                     dataView: { show: true, readOnly: false },
                     magicType: { show: true, type: ['line', 'bar', 'stack', 'tiled'] },
                     restore: { show: true },
                     saveAsImage: { show: true }
                 }
             },
             calculable: false,        
             xAxis: [{
             	show:false,
                 type: 'value',
                 axisLabel: {
                     show: false,
                     textStyle: {
                         color:'red',
                         
                     }
                 },
             }],
           yAxis: [{
             	 show:false,
                 type: 'category',
                 data: [' '],
                 axisLabel: {
                     show: false,
                     textStyle: {
                      color: 'red',
                    
                     }
                 },
                 axisLine: {
                     lineStyle:{
                     	width:0,
                         color: 'black',        

                     }
                 }
             }],

             series:[{
                     name: '<3000RMB',
                     type: 'bar',
                     stack: '总量',
                     itemStyle: { normal: { label: { show: true, position: 'insideRight' } } },
                     data: ['862'],
                   
                     legendHoverLink:false
                 },
                 {
                     name: '3001-5000RMB',
                     type: 'bar',
                     stack: '总量',
                     itemStyle: { normal: { label: { show: true, position: 'insideRight' } } },
                     data: ['383']
                 },
                 {
                     name: '5001-10000RMB',
                     type: 'bar',
                     stack: '总量',
                     itemStyle: { normal: { label: { show: true, position: 'insideRight' } } },
                     data: ["281"]
                 },
                 {
                     name: '10001-15000RMB',
                     type: 'bar',
                     stack: '总量',
                     itemStyle: { normal: { label: { show: true, position: 'insideRight' } } },
                     data: ["102"]
                 },
                 {
                     name: '>15000RMB',
                     type: 'bar',
                     stack: '总量',
                     itemStyle: { normal: { label: { show: true, position: 'insideRight' } } },
                     data: ['331']
                 }
             ],
             legend: {
                 data: ['<3000RMB', '3001-5000RMB', '5001-10000RMB', '10001-15000RMB', '>15000RMB'],
                 x:'center',
                 y:'bottom',
                 textStyle:{
                   color: '#fff'
               }
             },
         };
        myChart.setOption(option);

		window.addEventListener('resize', e => {
			myChart.resize();
		});                    
	}
	
	loadChartsEducation(ObjArr){
        let myChart = echarts.init(document.getElementById('chart-edu'));
        let option = {

                title: {
                    text: '',//
                    subtext: '',
                    x: 'center'
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c} ({d}%)"
                },
                
                series: [{
                    name: '访问来源',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '45%'],
                    data: [
                        { value: 33500, name: '高中(中专)及以下' },
                        { value: 21000, name: '本科' },
                        { value: 23400, name: '大专' },
                        { value: 1352, name: '硕士' },
                        { value: 1240, name: '博士' }
                    ],
                     label: {
                            normal: {
                                textStyle: {
                                    color: '#E9F1FB'
                                }
                            }
                      },
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        },
                        color: function(params) {            
                                   var colorList = [
                                          '#41B894','#53C6EA','#8C92D0','#565CAF','#55C5EA',
                                           '#FE8463','#9BCA63','#FAD860','#F3A43B','#60C0DD',
                                           '#D7504B','#C6E579','#F4E001','#F0805A','#26C0C0'
                                        ];
                                     
                                        return colorList[params.dataIndex]
                       },
                    }
                }]
            };
        myChart.setOption(option);
        window.addEventListener('resize', e => {
            myChart.resize();
        });      
	}
	//关键人生阶段
	
	loadChartsStage(){
        let myChart = echarts.init(document.getElementById('chart-stage'));
        let option = {
            title: {
                text: ' ',
                subtext: ' '
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c}%"
            },
            toolbox: {
                show: false,
                feature: {
                    mark: { show: true },
                    dataView: { show: true, readOnly: false },
                    restore: { show: true },
                    saveAsImage: { show: true }
                }
            },
           
            calculable: true,
            series: [ 
                {
                    name: '金字塔',
                    type: 'funnel',
                    x: '40%',
                    sort: 'ascending',
                    itemStyle: {
                        normal: {
                            color:function (params) {
                            	     // build a color map as your need.
                                        var colorList = [
                                          '#41B894','#53C6EA','#8C92D0','#565CAF','#55C5EA', '#43B894'
                                         
                                        ];
                                     
                                        return colorList[params.dataIndex];
                            },
                            label: {
                                position: 'left'
                            }
                        }
                    },
                    data: [
                        { value: 60, name: '老年黄金期' },
                        { value: 40, name: '事业发展期' },
                        { value: 20, name: '学生期' },
                        { value: 80, name: '事业成熟期' },
                        { value: 100, name: '职场初期' },
              
                    ]
                }
            ]
        };
         myChart.setOption(option);
        window.addEventListener('resize', e => {
            myChart.resize();
        });      
	}

	splitNumberInComma(num) {
		let str = num.toString();
		let arr = str.split('').reverse();
		let newArr = arr.map((item, index) => {
			return ((index + 1) % 3 === 0 && (index + 1) !== arr.length) ? item + ',' : item;
		})
		return newArr.join('').split('').reverse().join('');
	}
    testLogin(){

         var url='http://192.168.10.181:8081/mer-api/api/login';
    	 let formData=new FormData();
    	 formData.append('mobile','13612345678');
    	 formData.append("password",'admin');
       
    	 fetch(url,{
         
    	 	method:'POST',
    	 	body:formData
    	 }).then((res)=>res.text())
    	   .then((res)=>{
    	 	 
    	 })
         .catch((err)=>{
         	console.log(err);
         });
     
        
    }
	render() {
		return (
			<div className="portrait-container" >
				<div className="chart-container">
					<div className="chart-row chart-row1">
						<div className="chart1 relative">
							<div className="chart-title">
								<div >
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
								</div>
								<div className="title-text" onClick={()=>{this.testLogin()}}>
									性别比例
								</div>
							</div>
							<div id="chart-sex" className="chart chart-sex">
								<div className="sex-item">
									<img src={require('./images/man.png')} className="img-man" />
									<div className="sex-usercount">
										<div className="usercount-title">实时用户量</div>
										<div className="usercount-value1">{this.splitNumberInComma(this.state.realTimeUserMan)}</div>
										<div className="usercount-title">累计用户量</div>
										<div className="usercount-value2">{this.splitNumberInComma(this.state.totalUserMan)}</div>
									</div>
								</div>
								<div className="sex-item">
									<img src={require('./images/woman.png')} className="img-woman" />
									<div className="sex-usercount">
										<div className="usercount-title">实时用户量</div>
										<div className="usercount-value1">{this.splitNumberInComma(this.state.realTimeUserWoman)}</div>
										<div className="usercount-title">累计用户量</div>
										<div className="usercount-value2">{this.splitNumberInComma(this.state.totalUserWoman)}</div>
									</div>
								</div>
							</div>
							<img src={require("./images/angle.png")} className="img-corner" />
						</div>
						<div className="chart2 relative">
							<div className="chart-title">
								<div>
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
								</div>
								<div className="title-text">
									年龄分布
								</div>
							</div>
							<div className="thunder_chart chartbox">
                               <div id="chart-age"  className="chart"></div>
							</div>
							
							<img src={require("./images/angle.png")} className="img-corner" />
							<img src={require("./images/gear2.png")} className="img-gear2" />
						</div>
						<div className="chart3 relative">
							<div className="chart-title">
								<div>
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
								</div>
								<div className="title-text">
									收入水平分布
								</div>
							</div>
							<div className="thunder_chart salary_chart chartbox">
							   <div id="chart-salary" className="chart"></div>
							</div>
							<img src={require("./images/angle.png")} className="img-corner" />
						</div>
					</div>
					<div className="chart-row chart-row2">
						<div className="chart4 relative">
							<div className="chart-title">
								<div>
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
								</div>
								<div className="title-text">
									身份职业
								</div>
							</div>
							<div className="thunder_chart chartbox">
                               <div id="chart-profession" className="chart"></div>
							</div>
							
							<img src={require("./images/angle.png")} className="img-corner" />
						</div>
						<div className="chart5 relative">
							<div className="chart-title">
								<div>
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
								</div>
								<div className="title-text">
									受教育程度
								</div>
							</div>
							<div className="thunder_chart chartbox">
							   <div id="chart-edu" className="chart"></div>
							</div>
							
							<img src={require("./images/angle.png")} className="img-corner" />
							<img src={require("./images/gear3.png")} className="img-gear3" />
						</div>
						<div className="chart6 relative">
							<div className="chart-title">
								<div>
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
									<img src={require("./images/right.png")} className="img-right" />
								</div>
								<div className="title-text">
									关键人生阶段
								</div>
							</div>
							<div className="thunder_chart chartbox">
							  <div id="chart-stage" className="chart"></div>
							</div>
							
							<img src={require("./images/angle.png")} className="img-corner" />
						</div>
					</div>
				</div>
			</div>
		);
	}
}

export default Portrait;